package com.fumin.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Lingo on 2018/3/8.
 */
public class QcodeUtil {


    /**
     * 生成二维码图片
     * @author Lingo
     */
    public static byte[] getQrcodeImg(String content){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int width=300;
        int hight=300;
        String format="png";
        HashMap hints=new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级L,M,Q,H
        hints.put(EncodeHintType.MARGIN, 2); //边距
        BitMatrix bitMatrix= null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, hight, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        try {
            MatrixToImageWriter.writeToStream(bitMatrix, format, byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }
}
